<?php
namespace Manage\Controller;


class FinanceController extends CommonController {

    //发行通币
    public function Release(){
        $db = zyt_data_init();
        if( IS_POST ){
            $manager = '后台管理员';
            $post = I('post.');

            $number = (int)trim($post['number']);
            $hash   = $post['hash'];

            if( ! $number > 0 ){
                $this->error('请确认您的发行通币数量');
            }

            //防止重复提交订单
            if( compare_form_hash($hash) ){
                $sso_uid  = $this->sso_uid;
                $currency_data = $db->table('common_class')->field('common_class_id')->where("common_class_no = 'LB0002001'")->find();
                $currency = $currency_data['common_class_id'];

                $db->startTrans();
                $data['issue_time']    = time();
                $data['issue_count']   = $number;
                $data['issue_remarks'] = $post['remark'];
                $data['issue_user_name'] = $manager;
                $data['issue_currency']  = $currency;
                $db->updateUserTb($sso_uid, $number);
                $db->table('coins_issue')->add($data);
                $result = $db->commit();
                $result ? $this->success('您已成功发行了'.$number.'个通币') : $this->error('系统发生错误，所有操作已被撤销，请重试。');
            }
        }else{
            $current = $db->getUserCapital($this->sso_uid)[0]['tong_money_count'];
            $count = $db->table('coins_issue')->select('issue_count');

            foreach($count as $v){
                $sum[]=(float)$v['issue_count'];
            }
            $countsum=array_sum($sum);
            $this->assign('countsum',$countsum);
            $hash = form_hash();

            $this->assign('current', price($current, false));
            $this->assign('hash', $hash);
            $this->display();
        }

    }

    //查看发行日志
    public function ViewReleaseLog(){
        $db = zyt_data_init();

        $total = $db->table('coins_issue as A')->join('common_class as B', 'A.issue_currency', 'B.common_class_id')->order('A.issue_id desc')->count();

        //分页
        $nowpage = (int)I('get.page');
        $page = $nowpage > 0 ? $nowpage : 1;
        $pagesize = C('LIST_PAGE_SIZE');
        $list = $db->table('coins_issue')->join('common_class', 'issue_currency', 'common_class_id')->order('issue_id desc')->page($page, $pagesize)->select();
        $this->assign('pagesize', $pagesize);
        $this->assign('pages', ceil($total/$pagesize));
        $this->assign('total', $total);
        $this->assign('list', $list);
        $this->assign('nowpages', $page);
        $this->display('ReleaseLog');
    }

    //查看交易记录
    public function TradingRecords(){
        $db = zyt_data_init();
        $get = I('get.');

        $map = [];
        // >>> 平台筛选
        $platID = (int)$get['platform'];
        if($platID > 0){
            $map['A.money_log_platform_id'] = $platID;
        }

        // >>> 币种筛选
        $currencyID = (int)$get['currency'];
        if($currencyID > 0){
            $map['A.money_log_currency'] = $currencyID;
        }

        // >>> 交易类型筛选
        $tradeTypeID = (int)$get['trade_type'];
        if($tradeTypeID > 0){
            $map['A.money_log_class'] = $tradeTypeID;
        }

        // >>> 筛选交易时间
        $date  = trim($get['date']);
        if($date){
            $tmp = explode('~', $date);
            $start_date = trim($tmp[0]);
            $end_date   = trim($tmp[1]);
            $start = strtotime($start_date);
            $end   = strtotime($end_date) + 86400;  //end需要加一天，防止当天的数据搜索不出来
            $map['A.money_log_time'] = array('>' , $start);
            $map['A.money_log_time'] = array('<' , $end);
        }
        $this->assign('start',$tmp[0]);
        $this->assign('end',$tmp[1]);

        // >>> 交易流水/用户名筛选
        $kw = trim($get['keyword']);
        if(strlen($kw) > 0){
            $map['A.money_log_no'] = array('=', $kw, array('E.user_name', 'OR'));
            $map['E.user_name']    = array('LIKE', $kw , array('A.money_log_no', 'OR'));
        }

        //获取平台数据
        $platforms = $db->table('platform_info')->field('platform_id, platform_name')->select();
        //获取交易币种
        $currency  = $db->table('common_class')->field('common_class_id, common_class_name')->where("common_class_sort = 'LB0002'")->select();
        //获取交易类型
        $trade_type = $db->table('common_class')->field('common_class_id, common_class_name')->where("common_class_sort = 'LB0001'")->select();

        //列表数据
        $nowpage = (int)I('get.page');
        $page = $nowpage > 0 ? $nowpage : 1;
        $pagesize = C('LIST_PAGE_SIZE');

        $privilegeArr=array();
        $privilegeArr=$map;
        session('csvdata',$privilegeArr);

        $total = $db->table('money_log as A')
                   ->join('platform_info as B', 'A.money_log_platform_id', 'B.platform_id')
                   ->join('common_class as C', 'A.money_log_class', 'C.common_class_id')
                   ->join('common_class as D', 'A.money_log_currency', 'D.common_class_id')
                   ->join('User as E', 'A.money_log_master_user_id', 'E.user_id')
                   ->join('User as F', 'A.money_log_slave_user_id', 'F.user_id')
                   ->where($map)
                   ->count();
        $list = $db->table('money_log as A')
            ->field('A.money_log_id, A.money_log_time, A.money_log_no, A.money_log_desc, A.money_log_count, B.platform_name, C.common_class_name, D.common_class_name as currency, E.user_name as master, F.user_name as slave')
            ->join('platform_info as B', 'A.money_log_platform_id', 'B.platform_id')
            ->join('common_class as C', 'A.money_log_class', 'C.common_class_id')
            ->join('common_class as D', 'A.money_log_currency', 'D.common_class_id')
            ->join('User as E', 'A.money_log_master_user_id', 'E.user_id')
            ->join('User as F', 'A.money_log_slave_user_id', 'F.user_id')
            ->where($map)
            ->page($page, $pagesize)
            ->order('A.money_log_time desc')
            ->select();
        //-------------------------------
        $this->assign('platforms', $platforms);
        $this->assign('currency', $currency);
        $this->assign('tradeType', $trade_type);
        $this->assign('pagesize', $pagesize);
        $this->assign('pages', ceil($total/$pagesize));
        $this->assign('total', $total);
        $this->assign('list', $list);
        $this->assign('nowpages', $page);
        $this->display();
    }
    public function csv(){
        //导出数据
        $where=array();
        $where=session('csvdata');
        $db = zyt_data_init();
        $list = $db->table('money_log as A')
            ->field('A.money_log_time, A.money_log_no, A.money_log_desc, A.money_log_count, B.platform_name, C.common_class_name, D.common_class_name as currency, E.user_name as master, F.user_name as slave')
            ->join('platform_info as B', 'A.money_log_platform_id', 'B.platform_id')
            ->join('common_class as C', 'A.money_log_class', 'C.common_class_id')
            ->join('common_class as D', 'A.money_log_currency', 'D.common_class_id')
            ->join('User as E', 'A.money_log_master_user_id', 'E.user_id')
            ->join('User as F', 'A.money_log_slave_user_id', 'F.user_id')
            ->where($where)
            ->order('A.money_log_time desc')
            ->select();
        import('Org.Util.Csv');
        $csv = $csv = new \Csv();
        $csv_title=array('日期','交易流水号','交易说明','交易金额','交易平台','交易类型','交易币种','交易主体','交易客体');
        $csv->put_csv($list,$csv_title);
        session('csvdata',null);
    }

    //分红设置
    public function BonusConfig(){
        $db = zyt_data_init();
        $map['config_key'] = 'bonus_week_rate';
        if( IS_POST ){
            $post = I('post.');
            $data['config_value'] = number_format((float)trim($post['number']),4);
            if( $data['config_value'] >= 100 || $data['config_value'] <= 0 ){
                $this->error('请设置周利率在0-100%之间');
            }
            $result = $db->table('config')->data($data)->where($map)->save();
            $result ? $this->success('更新成功') : $this->error('更新失败');
        }else{
            $config      = $db->table('config')->where($map)->find();
            $bonus_total = $db->table('bonus_log')->field('SUM(bonus_log_num)')->select();
            $nowpage     = (int)I('get.page');
            $page        = $nowpage > 0 ? $nowpage : 1;
            $pagesize    = C('LIST_PAGE_SIZE');
            $pagetotal   = $db->table('bonus_log')->count();
            $list        = $db->table('bonus_log')->order('bonus_log_id desc')->page($page,$pagesize)->select();
            $this->assign('pages', ceil($pagetotal/$pagesize));
            $this->assign('bonus_list', $list);
            $this->assign('bonus_week_rate', $config['config_value']);
            $this->assign('bonus_total', price($bonus_total[0][''],false));
            $this->display();
        }
    }

    // Ajax获取分红设置
    public function getBonusConfig(){
        $response = [];
        $db = zyt_data_init();
        $map['config_key'] = 'bonus_week_rate';
        $config = $db->table('config')->where($map)->find();
        $response['rate'] = $config['config_value'];
        $sn = generate_order_sn('FH');
        session('BONUS_SN', $sn);
        $response['sn'] = $sn;
        $response['datetime'] = date('Y-m-d H:i:s', time());
        $this->ajaxReturn($response);
    }

    // 执行分红操作
    public function Bonus(){
        set_time_limit(0);
        $db = zyt_data_init();
        $sn = session('BONUS_SN');
        $result = $db->Bonus($sn);
        $bonus_total = $db->table('bonus_log')->field('SUM(bonus_log_num)')->select();
        $response = [];
        if($result['output'][0] == 1){
            // 执行成功
            $log = $result['list'][0];
            $response['code'] = 1;
            $log['bonus_log_consumed_num'] = price($log['bonus_log_consumed_num'], false);
            $log['bonus_log_num']          = price($log['bonus_log_num'], false);
            $log['bonus_log_tong_num']     = price($log['bonus_log_tong_num'], false);
            $log['bonus_total']            = price($bonus_total[0][''],false);
            $response['log']  = $log;
        }else{
            $response['code'] = 0;
        }
        $this->ajaxReturn($response);
    }

	//通币转账
	public function TbTransfer(){
		if(IS_POST){
			$db = zyt_data_init();
			$name=I('post.name');
			$hash=I('post.hash');
			$number=(float)I('post.number');
			if($number<0){$this->error('转账金额不能小于0');}
			$ckprice=check_price($number);
			if(!$ckprice){$this->error('转账金额小数最多2位');}
			if($name==''){$this->error('请输入转出账号');}
			if( compare_form_hash($hash) ) {
				$zytgf = $db->table('User as a')->join('user_capital as b ON a.user_id = b.capital_user_id')->where('b.capital_user_id=1')->find();//zytgf(转出用户)
				if ($zytgf['tong_money_count'] < 0) {
					$this->error('转出账号余额小于0');
				}
				if ((float)$zytgf['tong_money_count'] < $number) {
					$this->error('转出账号余额小于需转账余额,请去发行通币');
				}
				$where['a.user_name'] = $name;
				$user = $db->table('User as a')->join('user_capital as b ON a.user_id = b.capital_user_id')->where($where)->find();//转入用户
				if ($user['user_id'] < 0) {
					$this->error('你转入帐号不存在');
				} else {
					$paynotice_a = (float)$user['tong_money_count'];//支付前余额(转入)
					$paynotice_b = (float)$zytgf['tong_money_count'];//支付前余额(转出)

					$whereOperating['capital_user_id']=$user['user_id'];
					$money_log_no=generate_order_sn();
					$db->startTrans();
					$ru['tong_money_count'] = $paynotice_a + $number;
					$db->table('user_capital')->where($whereOperating)->save($ru);//收入
					$chu['tong_money_count'] = $paynotice_b - $number;
					$db->table('user_capital')->where("capital_user_id=1")->save($chu);//支出
					$remark = I('post.remark');
					$this->addTbTransferLog($remark, $zhu = $zytgf['user_id'], $ke = $user['user_id'], $count = '-' . $number, $trade = $paynotice_b,$money_log_no);//转出记录
					$this->addTbTransferLog($remark, $zhu = $user['user_id'], $ke = $zytgf['user_id'], $count = $number, $trade = $paynotice_a,$money_log_no);//转入记录
					$result = $db->commit();
					$result ? $this->success('转账成功') : $this->error('系统发生错误，所有操作已被撤销，请重试。');
				}
			}

		}else{
			$this->hash = form_hash();
			$this->display();
		}
	}
	//添加转账记录
	private function addTbTransferLog($remark,$zhu,$ke,$count,$trade,$money_log_no){
		$db = zyt_data_init();
		$class=$db->table('common_class')->where("common_class_no='LB0001010'")->find();
		$data = [];
		$data['money_log_no']=$money_log_no;
		$data['money_log_platform_id']=C('PLATFORM_ID');
		$data['money_log_class']=$class['common_class_id'];//交易类型
		$data['money_log_time']=time();
		$data['money_log_currency']=7;//交易币种
		$data['money_log_desc']=$remark;

		$data['money_log_pre_trade']=$trade;
		$data['money_log_master_user_id']=$zhu;
		$data['money_log_slave_user_id']=$ke;
		$data['money_log_count']=$count;
		$db->table('money_log')->data($data)->add();
	}
	public function TbTransfer_checkname(){
		if( IS_AJAX ){
			$db = zyt_data_init();
			$name=I('post.user_name');
			$where['user_name'] = $name;
			$info=$db->table('User')->where($where)->find();
			if($info){
				$result = true;
			}else{
				$result = false;
			}
			$this->ajaxReturn($result);
		}
	}

	//通币余额
	public function TbBalance(){
		$db = zyt_data_init();
		$nowpage = (int)I('get.page');
		$page = $nowpage > 0 ? $nowpage : 1;
		$pagesize = C('LIST_PAGE_SIZE');
		if( IS_POST ){
			$name=I('post.keyword');
			if($name==''||$name=='zytgf'){
				$this->redirect('/Finance/TbBalance');
			} else {
				$keyword['a.user_name']=$name;
				$list=$db->table('User as a')->join('user_capital b ON a.user_id = b.capital_user_id')->where($keyword)->select();
				$this->assign('list',$list);
			}
		}else{
			$total=$db->table('User as a')->join('user_capital as b ON a.user_id = b.capital_user_id')->count();
			$list=$db->table('User as a')->join('user_capital as b ON a.user_id = b.capital_user_id')->page($page, $pagesize)->select();
			$this->assign('list',$list);
		}
		$this->assign('pagesize', $pagesize);
		$this->assign('pages', ceil($total/$pagesize));
		$this->assign('total', $total);
		$this->assign('nowpages', $page);
		$this->display();
	}
}